package com.jinlejia.erp.ui.new_house.recommend;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivityRecommendClientsBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.new_house.adapter.RecommendHouseAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 推荐客户
 */
public class RecommendClientsActivity extends AppCompatActivity implements View.OnClickListener, OnDateSetListener, RecommendHouseAdapter.AddHouseEvent {

    private String customerCode = "";
    private ProgressDialog progressDialog;
    private boolean isRequest = false;


    private ActivityRecommendClientsBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_recommend_clients);
        binding.setEvent(this);
        EventBus.getDefault().register(this);
        initView();

        if( getIntent().hasExtra("csCode") ){
            binding.namePhoneLayout.setVisibility(View.VISIBLE);
            customerCode = getIntent().getStringExtra("csCode");
            binding.selectPhone.setText(getIntent().getStringExtra("phone"));
            binding.selectName.setText(getIntent().getStringExtra("cNmae"));
        }
    }
    private RecommendHouseAdapter adapter;
    private void initView() {
        progressDialog = new ProgressDialog(this, "请稍后...");
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        adapter = new RecommendHouseAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 20, Color.parseColor("#F4F4F4")));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        adapter.setAddHouseEvent(this);
        if (getIntent().hasExtra("houseCode")) {
            Intent intent = getIntent();
            String houseName = intent.getStringExtra("houseName");
            String houseCode = intent.getStringExtra("houseCode");
            adapter.setHouseName(houseCode,houseName,0);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 10) {
                binding.namePhoneLayout.setVisibility(View.VISIBLE);
                binding.selectName.setText(data.getStringExtra("name"));
                binding.selectPhone.setText(data.getStringExtra("tel"));
                customerCode = data.getStringExtra("code");
            } else if (requestCode >=100) {
                ArrayList<Map<String, String>> selectMap = (ArrayList<Map<String, String>>) data.getSerializableExtra("data");
                if (selectMap!=null && selectMap.size()>0){
                    for (Map<String, String> map:selectMap) {
                        String code = map.get("code");
                        String name = map.get("name");
                        adapter.addHouseName(code,name);
                    }
                }
            }
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_back:
                finish();
                break;
            case R.id.id_select_clients:
                Intent intent = new Intent(RecommendClientsActivity.this, CustomerListActivity.class);
                intent.putExtra("type", "select");
                startActivityForResult(intent, 10);
                break;
            case R.id.id_send_btn:
                if (!isRequest) {
                    //提交
                    String check = adapter.check();
                    if (TextUtils.isEmpty(binding.selectName.getText().toString())) {
                        CustomToast.showToast(this, "请从选择用户", 1500);
                    } else if (TextUtils.isEmpty(binding.selectPhone.getText().toString())) {
                        CustomToast.showToast(this, "请输入客户手机号", 1500);
                    } else if (!TextUtils.isEmpty(check)) {
                        CustomToast.showToast(this, check, 1500);
                    }else {
                        progressDialog.show();
                        isRequest = true;
                        submit();
                    }

                }
                break;
            default:
                break;
        }
    }

    private void submit() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("remark", binding.idInputNotes.getText().toString()); //备注(String)
            jsonObject.put("customerCode", customerCode); //客户编码(String)
            jsonObject.put("customerName", binding.selectName.getText().toString()); //客户姓名
            jsonObject.put("customerTel", binding.selectPhone.getText().toString()); //客户手机号
            jsonObject.put("recommendHouseList",adapter.getData());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(ApiConfig.RECOMMEND_CUSTOMER)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();
                        isRequest = false;
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        progressDialog.dismiss();
                        if (DataFilter.filter(RecommendClientsActivity.this, response)) {
                            CustomToast.showToast(RecommendClientsActivity.this, "推荐成功", 1500);
                            EventBus.getDefault().post("200", " ");
                            finish();
                        }
                        isRequest = false;
                    }
                });
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        String time = DateUtil.getTime(String.valueOf(millseconds));
        adapter.setTime(time,String.valueOf(millseconds),timePickerView.getTag());
    }

    @Override
    public void selectTime(Map<String, String> map, int position) {
        TimePickerDialog mDialogMonthDayHourMinute = new TimePickerDialog.Builder()
                .setType(Type.ALL)
                .setTitleStringId("到访时间")
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.yellow))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.colorAccent))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.black))
                .setCallBack(this)
                .build();
        mDialogMonthDayHourMinute.show(getSupportFragmentManager(), String.valueOf(position));
    }

    @Override
    public void selectHouse(Map<String, String> map, int position) {
        Intent intent1 = new Intent(RecommendClientsActivity.this, SelectHousesActivity.class);
        startActivityForResult(intent1, 100+position);
    }
}
